﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;

namespace PipelineDemo
{
    public class MyHttpContext
    {
           
    }

    public class MyApplicationBuilder
    {
        public delegate Task RequestDelegate(MyHttpContext context);

        private readonly IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>();


        public IApplicationBuilder New()
        {
            throw new NotImplementedException();
        }

        public MyApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middlewear)
        {
            _components.Add(middlewear);
            return this;
        }

        public MyApplicationBuilder Use(Func<MyHttpContext, Func<Task>, Task> middlewear)
        {
            return Use(next =>
            {
                return context =>
                {
                    Task simpleNext() => next(context);
                    return middlewear(context, simpleNext);
                };
            });
        }

        public RequestDelegate Build()
        {
            RequestDelegate app = (context) =>
            {
                Console.WriteLine("默认中间件");
                return Task.CompletedTask;
            };

            foreach (var component in _components.Reverse())
            {
                app = component(app);
            }

            return app;
        }
    }
}